//ajax函数
function ajax(options) {
  options = options || {};
  options.type = (options.type || 'GET').toUpperCase();
  options.dataType = options.dataType || 'json';
  var xhr;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    //ie6以下
    xhr = ActiveXObject('Microsoft.XMLHTTP');
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      var status = xhr.status;
      if (status >= 200 && status < 300) {
        options.success && options.success(xhr.responseText, xhr.responseXML);
      } else {
        options.error && options.error(status);
      }
    }
  }
  if (options.type == 'GET') {
    params = formatParams(options.data);
    xhr.open('GET', options.url + '?' + params, true);
    xhr.setRequestHeader("tenant", tenantId);
    xhr.send(null);
  } else if (options.type == 'POST') {
    params = options.data;
    xhr.open('POST', options.url, true);
    xhr.setRequestHeader("tenant", tenantId);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", "Basic c2N0dl91aTpzY3R2X3VpX3NlY3JldA==");
    // 2022.09.16 绵阳登录需求 增加token 字段
    var token = JSON.parse(localStorage.getItem("userResData")) ? JSON.parse(localStorage.getItem(
      "userResData")).token : ''
    if (token) {
      xhr.setRequestHeader("token", "Bearer " + token)
    }
    xhr.send(params);
  }
}

function formatParams(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  }
  return arr.join('&');
}